#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import gtk,gtk.glade
import datetime
import gobject
import cPickle as pickle

from wordpath import *
#from dictfile import DictFile
from record import Record
from sound import read, play
from widgets import show_info
from testword import TestWord

(
    COLUMN_ID,
    COLUMN_TITLE,
    COLUMN_GROUP,
    COLUMN_NUM,
    COLUMN_TIMES,
) = range(5)

class Revise():
    def __init__(self, wTree):
        self.wTree = wTree
        
#         self.rr = None
#         self.queue = []
#         self.keep = []

        # 主窗口
        self.window_revise = self.wTree.get_widget("window_revise")
        # 标题标签
        self.label_revise = self.wTree.get_widget("label_revise")
        # 左盒子标签
        self.vbox_revise = self.wTree.get_widget("vbox_revise")
        # 左列表
        self.listview = self.wTree.get_widget("treeview_revise")
        # 休息标签
        self.label_rest = self.wTree.get_widget("label_rest")
        self.hpaned_revise = self.wTree.get_widget("hpaned_revise")
        
        self.label_revise.set_markup('<span size="xx-large">单词复习-浏览</span>')

        # Stage 1, Confirm WordList
        self.create_reviselist()

#         # Stage 2, test function
# #         self.wordtest = TestWord(self.rr,
# #                     "revise",
# #                     self.reviselist,
# #                     self.label_revise,
# #                     self.create_model,
# #                     self.update_record)
# #         self.pack_start(self.wordtest, False, False, 10)

#     def update_record(self):
#         """更新纪录，如果已经是第6次了，则完成这个纪录，从待复习
#         队列中剔除，将queue和keep合并然后更新record纪录"""
#         if self.rr.time == 6:
#             self.rr.finish_recite()
#             self.queue.remove(self.rr)
#         else:
#             self.rr.next = self.rr.set_next()

#         f = file(os.path.join(os.path.expanduser("~"), ".wordjoy/record"), "wb")
#         self.queue.extend(self.keep)

#         for rr in self.queue:
#             pickle.dump(rr, f, True)
            
#         f.close()
#         self.rr = None
        
    def create_reviselist(self):
        self.create_listview()

#         if self.queue:
#             self.label_rest.hide()      # 隐藏休息提示
#             self.hpaned_revise.show()          # 显示

#             vbox = self.wTree.get_widget("vobx_unknow")

#             button_unknow.connect("clicked", self.start_revise_cb)

#         else:
#             self.label_revise.set_markup('<span size="xx-large">没有复习安排</span>')
#             self.label_rest.set_label("今天好好休息吧！")
#             self.label_rest.show()
#             self.hpaned_revise.hide()

#     def start_revise_cb(self, widget, data = None):
#         if self.rr:
#             self.wordtest.create_test(self.rr)
#             self.reviselist.hide()
#             self.label_revise.set_markup('<span size="xx-large">单词复习-测试</span>')
#             self.wordtest.entry.grab_focus()
#             self.wordtest.show()
#         else:
#             show_info("请选择你要复习的内容")

    def create_listview(self):

        self.listview.show()

        self.model = gtk.ListStore(COLUMN, COLUMN, COLUMN, COLUMN, COLUMN)

        self.listview.set_model(self.model)

        self.create_model()

        self.__add_title_column("ID", COLUMN_ID)
        self.__add_title_column("书名", COLUMN_TITLE)
        self.__add_title_column("组别", COLUMN_GROUP)
        self.__add_title_column("单词数", COLUMN_NUM)
        self.__add_title_column("第几次复习", COLUMN_TIMES)

        selection = self.listview.get_selection()
        selection.set_mode(gtk.SELECTION_SINGLE)
        selection.connect("changed", self.selection_changed)

    def __add_title_column(self, title, column_id):
        column = gtk.TreeViewColumn(title, gtk.CellRendererText(), text = column_id)
        column.set_sort_column_id(column_id)
        self.listview.append_column(column)
        
    def create_model(self):
        self.model.clear()
        self.keep = []
        self.queue = []
#         f = file(os.path.join(os.path.expanduser("~"), ".wordjoy/record"), "rb")
#         Loading = True

#         while Loading:
#             try:
#                 rr = pickle.load(f)
#             except pickle.UnpicklingError:
#                 print "截入错误，应该是空记录"
#             except EOFError:
#                 Loading = False
#                 print "载入完毕"
#             else:
#                 if datetime.date.today() >= rr.next:
#                     iter = self.model.append()
#                     self.queue.append(rr)
#                     self.model.set(iter,
#                         COLUMN_ID, len(self.queue) - 1,
#                         COLUMN_TITLE, rr.get_dict().INFO["TITLE"],
#                         COLUMN_GROUP, rr.group,
#                         COLUMN_NUM, len(rr.words),
#                         COLUMN_TIMES, rr.time)
#                 else:
#                     self.keep.append(rr)

#         f.close()

    def selection_changed(self, widget, data = None):
        model = widget.get_selected()[0]
        iter = widget.get_selected()[1]
        if iter:
            self.rr = self.queue[int(model.get_value(iter, COLUMN_ID))]
            self.wordtest.now = self.rr.words[0]
            self.wordtest.cn.set_text(self.rr.get_dict()[self.wordtest.now])
            self.wordtest.progress.set_text("第1个(共%d)" % self.rr.num)

if __name__ == "__main__":
    wTree = gtk.glade.XML(GLADE_PATH + "revise_test.glade")
    win = wTree.get_widget("window_revise")
    win.connect('destroy', lambda *w: gtk.main_quit())
    Revise(wTree)
    gtk.main()
